﻿<%@ WebHandler Language="C#" Class="_call" %>

using System;
using System.Web;
using System.IO;
using System.Xml;
using System.Web.SessionState;
using System.Collections.Generic;
using NS.Utilities;
using BLL;
using WechatModel;

public class _call : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        StreamWriter sw = new StreamWriter(context.Server.MapPath("~/t.txt"));
        try
        {
            //判断请求是否正确，公众号的参数是signature，企业号的参数应该是msg_signature
            if (context.Request.QueryString["signature"] == null ||
                context.Request.QueryString["timestamp"] == null ||
                context.Request.QueryString["nonce"] == null)
            {
                context.Response.Write("No Get Request");
                sw.WriteLine("No Get Request");
                return;
            }

            //微信传过来的GET参数
            string signature = context.Request.QueryString["signature"].ToString();
            string timestamp = context.Request.QueryString["timestamp"].ToString();
            string nonce = context.Request.QueryString["nonce"].ToString();
            //含有echostr参数时表示是首次接入验证
            if (context.Request.QueryString["echostr"] != null)
            {
                CheckIn(context, signature, timestamp, nonce);
                sw.WriteLine("验证接入");
                return;
            }
            sw.WriteLine(signature);
            sw.WriteLine(timestamp);
            sw.WriteLine(nonce);

            //加密消息内容
            if (context.Request.QueryString["msg_signature"] != null)
            {
                string msgSignature = context.Request.QueryString["msg_signature"].ToString();
                sw.WriteLine(msgSignature);
                //公众号接入验证
                //CheckIn(context);
                //获取POST来的数据
                StreamReader sr = new StreamReader(context.Request.InputStream);
                string data = sr.ReadToEnd();
                sr.Dispose();
                sw.WriteLine(data);
                if (!string.IsNullOrEmpty(data))
                {
                    //对密文进行解密
                    Wechat bll = new Wechat();
                    XmlDocument xDoc = bll.DecPublic(msgSignature, timestamp, nonce, data);
                    if (xDoc == null)  //解密失败
                    {
                        //sw.WriteLine("dataerror");
                        context.Response.Write("success");
                        return;
                    }
                    else  //解密成功
                    {
                        sw.WriteLine("dataright");
                        //判断消息类型，并取值处理
                        XmlNode root = xDoc.FirstChild;
                        string openid = root["FromUserName"].InnerText;  //用户OPENID
                        string msgType = root["MsgType"].InnerText;
                        string url = "http://" + context.Request.Url.Host + "/wechat/";
                        MessageBll mbll = new MessageBll();
                        //sw.WriteLine(msgType);
                        //事件推送
                        if (msgType == "event")
                        {
                            string eventType = root["Event"].InnerText.ToLower();
                            sw.WriteLine(eventType);
                            sw.WriteLine("openid:" + openid);

                            //关注事件
                            if (eventType == "subscribe")
                            {
                                CookieHelper.SetObject("openid", openid);
                                //是否已注册
                                Model.Member m = MemberService.GetMemberByOpenID(openid);
                                if (m != null)
                                {
                                    mbll.SendText(openid, string.Format("欢迎回来！<a href='{0}index.html'>点击预约</a>", url));
                                }
                                else
                                {
                                    mbll.SendText(openid, string.Format("欢迎关注爱尚洗车，我们为您提供优质的洗车服务！<a href='{0}login.html'>点击注册</a>", url));
                                }
                            }
                            else
                            {
                                context.Response.Write("success");
                            }
                        }
                        else if (msgType == "text")
                        {
                            string txt = root["Content"].InnerText;  //用户OPENID
                            if (txt.ToUpper() == "YGDL")
                            {
                                CookieHelper.SetObject("openid", openid);
                                //是否已激活
                                if (UserService.IsActivate(openid))
                                {
                                    mbll.SendText(openid, string.Format("欢迎回来！<a href='{0}emplist.html'>点击进入</a>", url));
                                }
                                else
                                {
                                    mbll.SendText(openid, string.Format("欢迎回来！<a href='{0}empactive.html'>点击登陆</a>", url));
                                }
                            }
                        }
                        else
                        {
                            context.Response.Write("success");
                        }
                    }
                }
                else
                {
                    context.Response.Write("success");
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            sw.WriteLine(ex.Message);
            sw.WriteLine(ex.Source);
            sw.WriteLine(ex.TargetSite.Name);
        }
        finally
        {
            sw.Close();
        }
        context.Response.Write("success");
    }

    /// <summary>
    /// 接入验证
    /// </summary>
    private void CheckIn(HttpContext context, string signature, string timestamp, string nonce)
    {
        try
        {
            string a = "";
            if (Wechat.CheckInPublic(signature, timestamp, nonce, out a))
            {
                context.Response.Write(context.Request.QueryString["echostr"]);
            }
            else
            {
                context.Response.Write("");
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(ex.Message);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}